<script setup>
import Sidebar from "../components/Sidebar.vue";
import {onMounted, ref, reactive} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import * as echarts from 'echarts';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 获取路由参数
const route = useRoute();
const router = useRouter();
const stationId = route.params.id;

// 返回上一页
const handleBack = () => {
  router.back();
};

// 站点信息数据
const siteInfo = ref({
  name: '',
  location: '',
  capacity: '',
  lastUpdate: '',
  stationName: '',
  updatedAt:''
});

// 回收记录数据
const recordsData = ref([]);

// 判断当前用户是否为管理员
const isAdmin = ref(false);

// 对话框显示状态
const dialogVisible = ref(false);

// 表单数据
const formData = reactive({
  stationId: '',
  wasteType: '',
  weight: '',
  volume: ''
});

// 表单规则
const rules = {
  wasteType: [{ required: true, message: '请选择垃圾种类', trigger: 'change' }],
  weight: [
    { required: true, message: '请输入重量', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '重量必须大于0', trigger: 'blur' }
  ],
  volume: [
    { required: true, message: '请输入体积', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '体积必须大于0', trigger: 'blur' }
  ]
};

// 垃圾种类选项
const wasteTypeOptions = [
  { value: '', label: '请选择垃圾种类' },
  { value: 1, label: '可回收物' },
  { value: 2, label: '有害垃圾' },
  { value: 3, label: '湿垃圾' },
  { value: 4, label: '干垃圾' }
];

// 表单引用
const formRef = ref(null);

// 获取回收记录数据
const fetchWasteRecords = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/waste/records/${stationId}`);
    if (response.data.code === 1) {
      recordsData.value = response.data.data;
    } else {
      console.error('获取回收记录失败:', response.data.message);
    }
  } catch (error) {
    console.error('获取回收记录失败:', error);
  }
};

// 获取站点详细信息
const fetchStationInfo = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/station/${stationId}`);
    if (response.data.code === 1) {
      const stationData = response.data.data;
      siteInfo.value = {
        id: stationData.stationId,
        name: stationData.stationName,
        location: stationData.location,
        capacity: stationData.capacity,
        currentCapacity: stationData.currentCapacity,
        lastUpdate: stationData.updatedAt
      };

      // 更新图表数据
      updateChart(stationData.currentCapacity, stationData.capacity);
    } else {
      console.error('获取站点详情失败:', response.data.message);
    }
  } catch (error) {
    console.error('获取站点详情失败:', error);
  }
};

// 更新图表数据
const updateChart = (usedCapacity, totalCapacity) => {
  const chartDom = document.getElementById('pieChart');
  const myChart = echarts.init(chartDom);
  const remainingCapacity = totalCapacity - usedCapacity;

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '站点使用情况',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {c}'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: [
          {
            value: usedCapacity,
            name: '已使用容量',
            itemStyle: {
              color: '#ff6b6b'
            }
          },
          {
            value: remainingCapacity,
            name: '剩余容量',
            itemStyle: {
              color: '#4ecdc4'
            }
          }
        ]
      }
    ]
  };
  myChart.setOption(option);
};

// 打开添加记录对话框
const openDialog = () => {
  formData.stationId = stationId;
  dialogVisible.value = true;
};

// 提交表单 并没有更新图表
const submitForm = async () => {
  if (!formRef.value) return;

  // 检查是否选择了垃圾类型
  if (!formData.wasteType) {
    ElMessage.warning("请选择至少一个有效的垃圾类型！");
    return;
  }
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 这里添加提交到后端的代码
        const response = await axios.post('http://localhost:8080/records/stationId', formData);
        console.log('提交数据:', formData);
        ElMessage.success('添加成功');
        dialogVisible.value = false;
        // 重新获取数据
        fetchWasteRecords();
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      }
    }
  });
};

// 更新站点信息 并没有更新图表
const updateStation = async () => {
  try {
    // 这里添加更新站点的代码
    const response = await axios.put('http://localhost:8080/station/update', { stationId });
    console.log('更新站点:', stationId);
    ElMessage.success('更新成功');
    // 重新获取站点信息
    fetchStationInfo();
  } catch (error) {
    console.error('更新失败:', error);
    ElMessage.error('更新失败');
  }
};

// 检查用户权限
const checkUserRole = () => {
  const userInfo = localStorage.getItem('user');
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo);
      isAdmin.value = user.role === 'Admin';
    } catch (e) {
      console.error('解析用户信息失败:', e);
      isAdmin.value = false;
    }
  } else {
    isAdmin.value = false;
  }
};

onMounted(() => {
  fetchStationInfo();
  fetchWasteRecords();
  checkUserRole();
});
</script>

<template>
  <div class="page-container">
    <div>
      <Sidebar/>
    </div>
    <div class="content-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="info-section">
            <div class="button-group">
              <el-button class="back-button" type="primary" @click="handleBack">返回</el-button>
              <el-button type="success" :disabled="!isAdmin" @click="openDialog">添加记录</el-button>
              <el-button type="warning" @click="updateStation">更新站点</el-button>
            </div>
            <el-descriptions title="站点详细信息" :column="1" border>
              <el-descriptions-item label="站点ID">{{ siteInfo.id }}</el-descriptions-item>
              <el-descriptions-item label="站点名称">{{ siteInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="站点位置">{{ siteInfo.location }}</el-descriptions-item>
              <el-descriptions-item label="站点最大容量">{{ siteInfo.capacity }}</el-descriptions-item>
              <el-descriptions-item label="站点当前容量">{{ siteInfo.currentCapacity }}</el-descriptions-item>
              <el-descriptions-item label="状态更新时间">{{ siteInfo.lastUpdate }}</el-descriptions-item>
            </el-descriptions>

            <el-row class="records-section">
              <el-col :span="24">
                <div class="table-container">
                  <h3>最近回收记录 只展示最近10条数据</h3>
                  <el-table :data="recordsData" style="width: 100%;">
                    <el-table-column prop="wasteTypeId" label="回收种类"/>
                    <el-table-column prop="weight" label="回收重量/Kg"/>
                    <el-table-column prop="volume" label="回收体积/单位"/>
                    <el-table-column prop="createdAt" label="回收时间"/>
                  </el-table>
                </div>
              </el-col>
            </el-row>

          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-section">
            <div id="pieChart" class="chart"></div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
  
  <!-- 添加记录对话框 -->
  <el-dialog
    v-model="dialogVisible"
    title="添加回收记录"
    width="30%"
    center
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="站点ID" prop="stationId">
        <el-input v-model="formData.stationId" disabled></el-input>
      </el-form-item>
      <el-form-item label="垃圾种类" prop="wasteType">
        <el-select v-model="formData.wasteType" placeholder="请选择垃圾种类">
          <el-option
            v-for="item in wasteTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="重量(kg)" prop="weight">
        <el-input v-model.number="formData.weight" type="number" placeholder="请输入重量"></el-input>
      </el-form-item>
      <el-form-item label="体积" prop="volume">
        <el-input v-model.number="formData.volume" type="number" placeholder="请输入体积"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.page-container {
  display: flex;
  height: calc(100vh - 120px);
}

.content-container {
  flex: 1;
  padding: 20px;
}

.info-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 400px;
}

.chart {
  width: 100%;
  height: 100%;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.back-button {
  margin-bottom: 0;
}

.records-section {
  margin-top: 20px;
}

.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-height: 22rem;
  overflow-y: auto;
}

.table-container h3 {
  margin-top: 0;
  margin-bottom: 20px;
}
</style>